package com.ebupt.migu.music.common.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author tz
 */
@Slf4j
public class EasyExcelUtil {

    public static void export(HttpServletResponse response, Class head, List data, String fileName){
        setResponse(response,fileName);
        try {
            EasyExcel.write(response.getOutputStream(),head).excelType(ExcelTypeEnum.XLSX).sheet(fileName).doWrite(data);
        } catch (IOException e) {
            log.error("excel生成失败");
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void setResponse(HttpServletResponse response, String fileName){
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String name = "";
        try {
            name = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            log.error("文件名编码失败！");
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + name + ".xlsx");
    }
}
